package com.zr.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.model.User;
import com.zr.service.FuncService;
import com.zr.service.UserService;
/**
 * 用户登录的servlet
 * @author Administrator
 *
 */
public class LoginController extends HttpServlet {
	FuncService fs=new FuncService();
	UserService us=new UserService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置字符编码
		 	req.setCharacterEncoding("utf8");
		 	resp.setCharacterEncoding("utf8");
		 	//接收页面传来的的请求的参数
			String uname  = req.getParameter("uname");
			String upsw = req.getParameter("upsw");
			if("on".equals(req.getParameter("remember"))){
				Cookie  namecookie  = new Cookie("uname", uname);
				namecookie.setMaxAge(60*60*24);
				Cookie  pswcookie  = new Cookie("upsw", upsw);
				pswcookie.setMaxAge(60*60*24);
				resp.addCookie(namecookie);
				resp.addCookie(pswcookie);
			}
			User currentUser = new User(uname, upsw);
			boolean  flag  = us.validateUser(currentUser);
			HttpSession  session = req.getSession();
			if(flag){
				User user=us.getOneUser(currentUser);
				session.setAttribute("currentUserFunc", user);
				session.setAttribute("currentUser", us.getOneUser(currentUser));
				session.setAttribute("LoginMsg", "登陆成功");
				req.getRequestDispatcher("main.jsp").forward(req, resp);
			}else{
				session.setAttribute("LoginMsg", "密码错误！");
				req.getRequestDispatcher("login.jsp").forward(req, resp);
			}
	}
}
